package com.qiyun.pptutil;

import com.alibaba.fastjson.JSONObject;
import com.coreoz.ppt.PptImageReplacementMode;
import com.coreoz.ppt.PptMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.POIXMLTypeLoader;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.openxmlformats.schemas.drawingml.x2006.main.CTTable;

import java.awt.Color;
import java.io.*;
import java.util.List;

public class PPTUtil {

    private XMLSlideShow ppt;

    private String templateBaseUrl="";

    private String imageBaseUrl="";


    static {

        POIXMLTypeLoader.setClassLoader(CTTable.class.getClassLoader());
    }



    public PPTUtil() {
        this.ppt = new XMLSlideShow();

    }

    public PPTUtil(String tUrl,String imgUrl) throws IOException {
        this.ppt = new XMLSlideShow();
        this.templateBaseUrl=tUrl;
        this.imageBaseUrl=imgUrl;
    }

    private XMLSlideShow switchTemplate(String templateName) {
        XMLSlideShow template = null;
        try {
            template =new XMLSlideShow(new FileInputStream(this.templateBaseUrl+templateName));
        } catch (IOException e) {
            template=new XMLSlideShow();
        }

        return template;
    }


    public void createPPTByTemplate(String data,String template) throws Exception {


//        Thread thread = Thread.currentThread();
//        thread.setContextClassLoader(thread.getContextClassLoader().getParent());

        JSONObject map=JSONObject.parseObject(data);

        PptMapper mapper=new PptMapper();//.hide("hidden", arg -> "true".equals(arg));

        map.forEach((k,v)->{
            if(StringUtil.startsWithIgnoreCase(k,"img_")){
                try {
                    if(StringUtils.isBlank((String) v)){
                        throw new Exception("图片不存在");
                    }
                    mapper.image(k,
                            this.getImageFromNetByUrl((String)v),
                            PptImageReplacementMode.RESIZE_ONLY);//(this.imageMap.get(k)));//

                } catch (Exception e) {
//                        e.printStackTrace();
//                        mapper.text(k, "图片加载失败");
                    mapper.hide(k);
                }
            }

            if(StringUtil.startsWithIgnoreCase(k,"text_")){
                System.out.println(k+"-----"+v);
                mapper.text(k, v);
            }
        });


        XMLSlideShow slideShow= mapper.processTemplate(switchTemplate(template));

        List<XSLFSlide> slide=slideShow.getSlides();

        ppt.setPageSize(slideShow.getPageSize());

        for(int z=0;z<slide.size();z++){

            XSLFSlide slide1= ppt.createSlide().importContent(slide.get(z));
            slide1.getBackground().setFillColor(new Color(18,48,119));
        }




        slideShow.close();


    }

    public byte[] write() throws IOException {
        byte[] content =new byte[]{};

//        OutputStream os = new FileOutputStream("generated.pptx");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        this.ppt.write(os);

        content = os.toByteArray();
        os.close();

        return content;
    }

    public void close() throws IOException {
        if(this.ppt!=null){
            this.ppt.close();
        }
    }



    private byte[] getImageFromNetByUrl(String strUrl) throws IOException {


//        URL url = new URL(strUrl);
//        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//        conn.setRequestMethod("GET");
//        conn.setConnectTimeout(2 * 1000);
//
//        InputStream inStream = conn.getInputStream();//通过输入流获取图片数据

        FileInputStream inputStream= new FileInputStream(this.imageBaseUrl+strUrl);
        byte[] bytes=IOUtils.toByteArray(inputStream);
        inputStream.close();


        return bytes;



    }




//    public static void main(String[] args) throws Exception {
//
//        double start=System.currentTimeMillis();
//        String[] templates={"yinghuan.pptx","yinghuanImg.pptx"};
//        PPTUtil pptUtil=new PPTUtil("/Users/lvbin/Desktop/","/");
//
////        System.out.println("-------------end---------------"+(System.currentTimeMillis()-start)/1000);
//
//        String tableData="{" +
//                "'text_yhzs':'大洋镇\n住建局',"+
//                "'text_zgyhs':'大洋镇\n住建局',"+
//                "'text_zrdw':'大洋镇\n住建局',"+
//                "'text_ywdw':'大洋镇新建路60号凯旋厨卫',"+
//                "'text_ywnr':'瓶库外墙无明显的禁止烟火标志，库内地面非撞击时不发生火花的面层；\n灭火器已失效；\n瓶库未配置燃气浓度检测报警器。\n',"+
//                "'text_zgdw':'瓶库外墙已设置禁止烟火标志；\n库内地面已整改为撞击时不发生火花的面层；\n配备新灭火器；\n配备燃气浓度检测报警器。\n'"+
//                "}" ;
//
//        String imgData1="{" +
//                "'text_yhdw':'凯旋厨卫111',"+
//                "'img_zgq_1':'/Users/lvbin/Desktop/splash.png',"+
//                "'img_zgq_2':'/Users/lvbin/Desktop/splash.png',"+
//                "'img_zgq_3':'/Users/lvbin/Desktop/splash.png',"+
//                "'img_zgh_1':'/Users/lvbin/Desktop/splash.png',"+
//                "'img_zgh_2':'/Users/lvbin/Desktop/splash.png',"+
//                "'img_zgh_3':'/Users/lvbin/Desktop/splash.png',"+
//                "'text_zgh':'设置严禁烟火标志'"+
//                "}" ;
//
//        String imgData="[";
//        for(int i=0;i<100;i++){
//            imgData +="{" +
//                    "'text_yhdw':'凯旋厨卫"+i+"',"+
//                    "'img_zgq_1':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'img_zgq_2':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'img_zgq_3':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'img_zgh_1':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'img_zgh_2':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'img_zgh_3':'http://47.100.165.34:8081/FireImage//20181010/035833images.jpg',"+
//                    "'text_zgh':'设置严禁烟火标志'"+
//                    "}," ;
//        }
//        imgData=imgData.substring(0,imgData.length()-1);
//        imgData +="]";
//
//        double end=0;
////        pptUtil.getImageMap(pptUtil,imgData);
////
////        System.out.println(pptUtil.imageMap);
//
//
//        for(int i=0;i<100;i++){
//            tableData="{" +
//                    "'text_yhzs':'大洋镇\n住建局123"+i+"',"+
//                    "'text_zgyhs':'大洋镇\n住建局123',"+
//                    "'text_zrdw':'大洋镇\n住建局"+i+"',"+
//                    "'text_ywdw':'大洋镇新建路60号凯旋厨卫',"+
//                    "'text_ywnr':'瓶库外墙无明显的禁止烟火标志，库内地面非撞击时不发生火花的面层；\n灭火器已失效；\n瓶库未配置燃气浓度检测报警器。\n',"+
//                    "'text_zgdw':'瓶库外墙已设置禁止烟火标志；\n库内地面已整改为撞击时不发生火花的面层；\n配备新灭火器；\n配备燃气浓度检测报警器。\n'"+
//                    "}" ;
//
//            pptUtil.createPPTByTemplate(tableData, "yinghuan.pptx");
////            pptUtil.createPPTByTemplate(tableData, "yinghuan.pptx");
////            pptUtil.createPPTByTemplate(imgData1, "yinghuanImg.pptx");
//        }
//
////        ExecutorService exe = Executors.newFixedThreadPool(3);
//
//
////        for(int i=0;i<10;i++){
////
////
////            exe.execute(new Thread(
////                    () -> {
////                        try {
////                            pptUtil.createPPTByTemplate(tableData, "yinghuan.pptx");
////                            pptUtil.createPPTByTemplate(imgData, "yinghuanImg.pptx");
////
////                        } catch (Exception e) {
////                            e.printStackTrace();
////                        }
////
////                    }
////            ));
////
////
////        }
////
////        exe.shutdown();
////        while (true) {
////            if (exe.isTerminated()) {
////                System.out.println("结束了！");
////                break;
////            }
////        }
//
////        pptUtil.write(out);
//
//        System.out.println(pptUtil.write());
////        PPTUtil.writeBytesToFile(pptUtil.write());
//        pptUtil.close();
//        end=System.currentTimeMillis();
//        System.out.println("-------------end---------------"+(end-start)/1000);
//
//
//
////        System.out.println("Templated presentation generated in " + Paths.get("generated.pptx").toAbsolutePath());
//
//
////        mapper
////                .text("var1", "Content replaced")
////                .text("var3", "Header cell replaced")
////                .text("var4", "Content cell replaced")
////                .image("image1", IOUtils.toByteArray(PPTUtil.class.getResourceAsStream("/images/replacedImae.jpg")),
////                        PptImageReplacementMode.RESIZE_ONLY)
////                .image(
////                        "image2",
////                        IOUtils.toByteArray(PPTUtil.class.getResourceAsStream("/images/replacedImage.jpg")),
////                        PptImageReplacementMode.RESIZE_ONLY
////                )
////                .styleText("style", textRun -> {
////                    textRun.setBold(true);
////                    textRun.setFontColor(Color.GREEN);
////                })
////                .styleShape("percentage", shape -> {
////                    Rectangle2D shapeAnchor = shape.getAnchor();
////                    shape.setAnchor(new Rectangle2D.Double(
////                            shapeAnchor.getX(),
////                            shapeAnchor.getY(),
////                            // widen the shape of 20%
////                            shapeAnchor.getWidth() * 1.2,
////                            shapeAnchor.getHeight()
////                    ));
////                });
//    }



//    public static void writeBytesToFile(byte[] bs) throws IOException{
//
//        OutputStream out = new FileOutputStream("generated.pptx");
//        InputStream is = new ByteArrayInputStream(bs);
//        byte[] buff = new byte[1024];
//        int len = 0;
//        while((len=is.read(buff))!=-1){
//            out.write(buff, 0, len);
//        }
//        is.close();
//        out.close();
//    }

}
